
from sqlalchemy import and_
from app.core.exception import ApiException
from app.entity.projectUser import ProjectUser
from app.service.projectMessage import ProjectMessageService
from app.service.user import UserService


class ProjectUserService:
    def joinProject(projectId,UserId,isAdmin):
        if ProjectUserService.inProject(projectId,UserId):
            raise ApiException("你已经加入该项目")
        projectUser=ProjectUser()
        projectUser.projectId=projectId
        projectUser.userId=UserId
        projectUser.isAdmin=isAdmin
        joinUserInfo=projectUser.getUserInfoAttr()
        projectUser.save()
        adminUser=ProjectUserService.getProjectAdmins(projectId)
        for admin in adminUser:
            ProjectMessageService.sendSystemMessage(UserId,admin.id,"有新用户加入项目",f"用户：{joinUserInfo['nickname']} 加入了项目!")
        return projectUser
    
    def getProjectUser(projectId,userId)->ProjectUser:
        return ProjectUser().query().where(and_(ProjectUser.projectId==projectId,ProjectUser.userId==userId)).first()
    
    def getProjectUsers(projectId)->list[ProjectUser]:
        return ProjectUser().query().where(and_(ProjectUser.projectId==projectId)).all()
    
    def getProjectAdmins(projectId)->list[ProjectUser]:
        return ProjectUser().query().where(and_(ProjectUser.projectId==projectId,ProjectUser.isAdmin=='Y')).all()
    
    def inProject(projectId,userId)->bool:
        return ProjectUser().query().where(and_(ProjectUser.projectId==projectId,ProjectUser.userId==userId)).count()>0
    
    def deleteProjectUsers(projectId,userIds:list[int]):
        from app.service.project import ProjectService
        project=ProjectService.getProjectById(projectId)
        ProjectUser().query().where(and_(ProjectUser.userId.in_(userIds),ProjectUser.userId!=project.createBy)).delete()
    
    